package com.nursinghome.emp.controller;

import com.nursinghome.bean.Holidays;
import com.nursinghome.bean.RespBean;
import com.nursinghome.emp.service.EmpHolidaysService;
import com.nursinghome.exception.NurisingHomeException;
import com.nursinghome.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/emp/holidays")
public class EmpHolidaysController {
    @Autowired
    private EmpHolidaysService empHolidaysService;
    //查询护工的请假记录
    @GetMapping
    public RespBean selectByMid(@RequestHeader(value = "token", required = false) String token){
        //获取当前用户id
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer mid = (Integer) map.get("mid");
        List<Holidays> holidays = empHolidaysService.selectByMid(mid);

        return RespBean.ok("",holidays);
    }

    //护工请假
    @PostMapping
    public RespBean insert(@RequestBody @Validated Holidays holidays, @RequestHeader(value = "token", required = false) String token) throws NurisingHomeException {
        //获取当前用户id
        //判断令牌
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer jwtMid = (Integer) map.get("mid");
        if (jwtMid == null) {
            return RespBean.error("令牌信息不正确");
        }
        holidays.setMid(jwtMid);
        if (!empHolidaysService.insert(holidays)) {
            return RespBean.error("操作失败");
        }
        return RespBean.ok("请假成功待审核！");
    }
    //查询当前时段是否有请假
    @GetMapping( "/bydata")
    public RespBean selectByData(String data, @RequestHeader(value = "token", required = false) String token){
        //时区转换
        if (data.length()>0 && data!=null){
            ZonedDateTime zdt = ZonedDateTime.parse(data);
            // 加上八小时
            ZonedDateTime newZdt = zdt.plusHours(8);
            // 转换为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
            data = newZdt.format(formatter);
        }
        //获取当前用户id
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer mid = (Integer) map.get("mid");
        if (mid == null) {
            return RespBean.error("令牌信息不正确");
        }
        //根据据时间查询
        Holidays holidays = empHolidaysService.selectByData(data, mid);
        return RespBean.ok("",holidays);
    }
}
